package com.teatrace.commons.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.log4j.Logger;

public class EncodingFilter implements Filter {
	
	private static Logger logger = Logger.getLogger(EncodingFilter.class);
	
	private static String encoding = "UTF-8";

	public void destroy() {
		logger.info("EncodingFilter destroy");
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		request.setCharacterEncoding(encoding);
		response.setCharacterEncoding(encoding);
		
		chain.doFilter(request, response);
	}

	public void init(FilterConfig config) throws ServletException {
		String configEncoding = config.getInitParameter("encoding");
		if(configEncoding != null) {
			encoding = configEncoding;
		}
		logger.info("EncodingFilter init, encoding: " + encoding);
	}

}
